package com.klm.easymq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * 数据库初始化配置
 * @author klm
 */
@Slf4j
@Component
public class DatabaseInitConfig implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        log.info("开始初始化数据库...");
        initDatabase();
        log.info("数据库初始化完成");
    }

    /**
     * 初始化数据库表结构
     */
    private void initDatabase() {
        try {
            // 检查数据库连接
            log.info("检查数据库连接...");
            jdbcTemplate.queryForObject("SELECT 1", Integer.class);
            log.info("数据库连接正常");

            // 创建messages表
            log.info("开始创建 messages 表...");
            String createTableSql = """
                CREATE TABLE IF NOT EXISTS messages (
                    trace_id TEXT PRIMARY KEY,
                    topic TEXT,
                    status TEXT,
                    consume_time INTEGER,
                    error_msg TEXT,
                    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
                """;
            
            jdbcTemplate.execute(createTableSql);
            log.info("数据库表 messages 创建成功");
            
            // 验证表是否创建成功
            String checkTableSql = "SELECT COUNT(*) FROM messages";
            Integer count = jdbcTemplate.queryForObject(checkTableSql, Integer.class);
            log.info("messages 表验证成功，当前记录数: {}", count);
            
        } catch (Exception e) {
            log.error("数据库表初始化失败", e);
            throw new RuntimeException("数据库初始化失败: " + e.getMessage(), e);
        }
    }
} 